<template>
  <div>
    <div>
      <el-tree
        :data="menu"
        :props="defaultProps"
        show-checkbox
        :expand-on-click-node="false" :default-expanded-keys="defaultexpandedkeys" node-key="mid"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button  type="text" size="mini" @click="() => append(data)">
              添加
            </el-button>
            <el-button 
              type="text"
              size="mini"
              @click="() => remove(node, data)"
            >
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menu: [],
      defaultProps: {
        children: "children",
        label: "mname",
      },
      defaultexpandedkeys:[]
    };
  },
  created() {
    this.getAllMenus();
  },
  methods: {
    append(data) {
      console.log("append:data:",data)
    },

    remove(node, data) {
      // //弹框，确认
      console.log("remove",node,data);
      // console.log("remove",data.mid);
      this.$axios.get("http://localhost:8080/menu/remove/"+data.mid).then((resp) => {
        if (resp.data.code == 200) {
          this.$message('删除成功');
          //刷新菜单
          this.getAllMenus();
          // console.log(node.parent.data.mid);
          this.defaultexpandedkeys.push(node.parent.data.mid);
        }else{
          this.$message(resp.data.data);
        }
      });
    },
    getAllMenus() {
      this.$axios.get("http://localhost:8080/menu/get/all").then((resp) => {
        if (resp.data.code == 200) {
          this.menu = resp.data.data;
          // let allMenus=resp.data.data;
          // for(let menu of allMenus){
          //   if(menu.pmid==0){
          //     //添加一级菜单
          //     this.menu.push(menu);
          //     //给当前菜单添加子菜单
          //     let children=[];
          //     for(let submenu of allMenus){
          //       if(submenu.pmid==menu.mid){
          //         children.push(submenu);
          //       }
          //     }
          //     //children数组作为一个菜单对象的属性
          //     menu.children=children;
          //   }
          // }
        }
      });
    },
  },
};
</script>

<style>
</style>